package net.slidinglive.utilities.fragment;

import java.util.ArrayList;
import java.util.List;

import net.slidinglive.utilities.R;
import net.slidinglive.utilities.adapter.ContactAdapter;
import net.slidinglive.utilities.adapter.ContactSourceAdapter;
import net.slidinglive.utilities.enumeration.ContactSource;
import net.slidinglive.utilities.model.Contact;
import net.slidinglive.utilities.util.ContactHelper;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * @author Sebastian Hoffmann <bo.hoffi@gmail.com>
 */
public class ContactsFragment
        extends AbstractFragment {

    private Spinner contactSourceSpinner;

    private ContactAdapter contactAdapter;

    public ContactsFragment() {

    }

    public ContactsFragment(final int layoutId, final String title) {

        super(layoutId, title);
    }

    /*
     * (non-Javadoc)
     * 
     * @see net.slidinglive.utilities.fragment.AbstractFragment#prepareView()
     */
    @Override
    protected void prepareView() {

        this.contactSourceSpinner = (Spinner) this.view.findViewById(R.id.contacts_source);
        this.contactSourceSpinner.setAdapter(new ContactSourceAdapter(this.getActivity()));

        final ImageButton refreshButton = (ImageButton) this.view.findViewById(R.id.contacts_btn_refresh);
        refreshButton.setOnClickListener(this.refreshButtonClickListener);

        final ListView contactList = (ListView) this.view.findViewById(R.id.contacts_list);
        this.contactAdapter = new ContactAdapter(this.getActivity());
        contactList.setAdapter(this.contactAdapter);
    }

    /**
     * The callback, when the user starts the search.
     */
    private final View.OnClickListener refreshButtonClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            final ContactSource contactSource =
                    (ContactSource) ContactsFragment.this.contactSourceSpinner.getSelectedItem();

            List<Contact> contactsToShow = null;

            if (contactSource == ContactSource.EXISTING) {

                contactsToShow = ContactHelper.getExistingContacts(ContactsFragment.this.getActivity());

            } else if (contactSource == ContactSource.BACKUP) {

                contactsToShow = new ArrayList<Contact>();

            } else {

                contactsToShow = ContactHelper.getExistingContacts(ContactsFragment.this.getActivity());
            }

            ContactsFragment.this.contactAdapter.removeAll();
            ContactsFragment.this.contactAdapter.addAll(contactsToShow);
        }
    };
}